/**
 * ajax请求html页面
 * @param url
 * @param data
 * @returns {String}
 */
function ajaxHtml(url,callback) {
    var load = loading();
    $.ajax({
        type: "get",
        url: encodeURI(encodeURI(url)),
        dataType: "html",
        contentType: "application/x-www-form-urlencoded; charset=UTF-8",
        async: true,
        cache: false,
        success: function (response) {
            closeLoad(load)
            callback(response)
        },
        error: function () {
            closeLoad(load)
        }
    });
}

/**
 * ajax异步请求
 * @param async 是否异步
 * @param url   请求地址
 * @param data  请求参数
 * @param done  请求成功
 * @param fail  请求失败
 */
function get(url, done, fail) {
    var load = loading();
    var settings = {
        async: true,
        url: encodeURI(encodeURI(url)),
        contentType: "application/x-www-form-urlencoded; charset=UTF-8",
        type: "GET",
        cache: false,
        dataType: "json"
    };
    $.ajax(settings).done(function (response) {
        done(response);
        closeLoad(load)
    }).fail(function () {
        fail();
        closeLoad(load)
    });
}

function post(url, data, done, fail) {
    var load = loading();
    var settings = {
        async: true,
        url: encodeURI(encodeURI(url)),
        contentType: "application/x-www-form-urlencoded; charset=UTF-8",
        type: "POST",
        cache: false,
        data: data,
        dataType: "json"
    };
    $.ajax(settings).done(function (response) {
        done(response);
        closeLoad(load)
    }).fail(function () {
        fail();
        closeLoad(load)
    });
}
function ajaxFormData(url,formData,done,fail){
    var load = loading();
    $.ajax({
        url: url,
        type: 'POST',
        data: formData,
        async: true,
        cache: false,
        contentType: false,
        processData: false,
        success: function (res) {
            done(res);
            closeLoad(load)
        },
        error: function () {
            fail();
            closeLoad(load)
        }
    });
}
/**
 * post同步请求
 * @param url
 * @param data
 * @param done
 * @param fail
 */
function postSync(url, data, done, fail) {
    var load = loading();
    var settings = {
        async: false,
        url: encodeURI(encodeURI(url)),
        contentType: "application/x-www-form-urlencoded; charset=UTF-8",
        type: "POST",
        cache: false,
        data: data,
        dataType: "json"
    };
    $.ajax(settings).done(function (response) {
        closeLoad(load)
        return done(response);
    }).fail(function () {
        closeLoad(load)
        return fail();
    });
}

/**
 * 将图片转成base64
 * @param file
 * @returns {*}
 */
function getObjectURL(file) {
    var url = null;
    if (window.createObjectURL != undefined) {
        url = window.createObjectURL(file)
    } else if (window.URL != undefined) {
        url = window.URL.createObjectURL(file)
    } else if (window.webkitURL != undefined) {
        url = window.webkitURL.createObjectURL(file)
    }
    return url
}

function configModal(selector, title, content) {
    $(selector).find(".modal-title").text(title);
    $(selector).find(".modal-body").html(content);
}

function $$(obj) {
    return $(obj).val()
}

function warning(text, closeBtn, callback) {
    return layer.alert(text, {icon: 0, closeBtn: closeBtn == false ? 0 : 1, title: "警告", btn: "确定"}, callback)
}

function success(text, closeBtn, callback) {
    return layer.alert(text, {icon: 1, closeBtn: closeBtn == false ? 0 : 1, title: "成功", btn: "确定"}, callback)
}

function error(text, closeBtn, callback) {
    return layer.alert(text, {icon: 2, closeBtn: closeBtn == false ? 0 : 1, title: "错误", btn: "确定"}, callback)
}

function systemErr() {
    return layer.alert("网络连接失败或系统异常", {icon: 2, closeBtn: 1, title: "错误", btn: "确定"})
}

function question(text, closeBtn, callback) {
    return layer.alert(text, {icon: 3, closeBtn: closeBtn == false ? 0 : 1, title: "疑问", btn: "确定"}, callback)
}

function confirm2(text, callback) {
    var index = layer.confirm(text, {
        icon: 3
    }, function () {
        layer.close(index)
        return callback();
    }, function () {
        layer.close(index)
    });
}

function msg(text) {
    layer.msg(text)
}

function loading() {
    return layer.load(0, {shade: [0.3, '#000']})
}

function closeLoad(load) {
    layer.close(load)
}

/**
 * 文字长度
 * @param str
 * @returns {Number}
 */
function len(str) {
    return str?$.trim(str).length:0;
}
/**
 * 文字是否为空
 * @param str
 * @returns {boolean}
 */
function isEmpty(str) {
    if (!str) {
        return true;
    }
    return len(str) === 0;
}

var parseDate = function (dateString) {
    return new Date(Date.parse(dateString.replace(/-/g, "/")));
};

String.prototype.trim = function (str) {
    return str?str.replace(/^\s+|\s+$/gm,''):"";
}
Date.prototype.format = function (format) {
    var date = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S+": this.getMilliseconds()
    };
    if (/(y+)/i.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in date) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1
                ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
        }
    }
    return format;
}

function DateFormat(date, fmt){
    if (arguments.length != 2) // 参数个数校验
        throw Error('arguments长度不合法');
    if (!date || (typeof date != 'object') || (d.constructor != Date)) // 参数合法性校验
        date = new Date(new Date().format(date))
    // throw Error(arguments[0] + ':类型不为Date类型');
    if (/H+/.test(fmt) && /h+/.test(fmt))
        throw Error("小时格式错误，同类型只能连续出现一次！");
    /* 模板参数校验，正则验证方法 */
    var verify = function(Rex ){
        var arr = new RegExp(Rex).exec(fmt); // 获得匹配结果数组
        if (!arr) // 匹配失败返回
            return "";
        if (fmt.split(Rex).length > 2) // 同一类型间隔出现多次
            throw Error("fmt格式错误：同类型只能连续出现一次！");
        return arr[0];
    };
    /**
     * 提供月、天、时、分、秒通用匹配替换
     * @param {对象o属性key} r
     * @param {r对应正则对象} rex
     **/
    var common = function(r, rex) {
        if(len !=1 && len !=2)
            throw Error("月份格式错误:M只能出现1/2次");
        len == 2 ? fmt=fmt.replace(rex, o[r].length==1 ? "0"+o[r] : o[r]) : fmt=fmt.replace(rex, o[r]);
    }
    var o = { // 数据存储对象
        "y+": date.getFullYear() + "", // 年
        "q+": Math.floor((date.getMonth() + 3) / 3), // 季度
        "M+": date.getMonth() + 1 + "", // 月
        "d+": date.getDate() + "", // 日
        "H+": date.getHours() + "", // 24时
        "h+": date.getHours() + "", // 12时
        "m+": date.getMinutes() + "", // 分
        "s+": date.getSeconds() + "", // 秒
        "S+": date.getMilliseconds() // 毫秒
    }
    for(var r in o) {
        var rex, len, temp;
        rex = new RegExp(r);
        temp = verify(rex); // 匹配所得字符串
        len = temp.length; // 长度
        if(!len || len == 0)
            continue;
        if(r == "y+") {
            if(len !=2 && len != 4)
                throw Error("年份格式错误:y只能出现2/4次");
            len == 2 ? fmt=fmt.replace(rex, o[r].substr(2,3)) : fmt=fmt.replace(rex, o[r]);
        } else if(r == "q+") {
            if(len != 1)
                throw Error("季度格式错误:q只能出现1次");
            fmt=fmt.replace(rex, o[r]);
        } else if(r == "h+") {
            if(len !=1 && len !=2)
                throw Error("小时格式错误:h只能出现1/2次");
            var h = (o[r] > 12 ? o[r]-12 : o[r]) + "";
            len == 2 ? fmt=fmt.replace(rex, h.length==1 ? "0"+h : h) : fmt=fmt.replace(rex, h);
        } else if(r == "S+") {
            if(len != 1)
                throw Error("毫秒数格式错误:S只能出现1次");
            fmt=fmt.replace(rex, o[r]);
        }else {  // (r=="M+" || r=="d+" || r=="H+" || r=="m+" || r=="s+")
            common(r, rex)
        }
    }
    return fmt;
}

function timestampToDate(timestamp) {
    if(!timestamp){
        return null;
    }
    return new Date(timestamp).format("yyyy-MM-dd hh:mm")
}

